API_KEY = "sk-645190d55952481685d26e2ef8303915"
from flask import Flask, request, jsonify, send_file, render_template, send_from_directory
from flask_cors import CORS
import os
from api import text_to_comic
from api import image_to_comic
from api.style_manager import get_styles, save_custom_style
from api.story_generator import generate_story
import re
import requests
import json
from dashscope import ImageSynthesis
from http import HTTPStatus
from werkzeug.utils import secure_filename
completions_url = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions'
image_synthesis_url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis'
tasks_status_url = 'https://dashscope.aliyuncs.com/api/v1/tasks/'


def generate_a_story(text, style):
    # 构造系统提示
    system_prompt = f"""你是一个漫画脚本作家。将以下故事分成6个连贯的漫画面板，每个面板用一句话描述画面内容，漫画风格：{style}。返回JSON格式：["描述1", "描述2", ...]"""

    # 构造消息
    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": text}
    ]

    # 调用AI API
    response = requests.post(
        completions_url,
        json={
            "model": "qwen-plus",
            "messages": messages
        },
        headers={
            'Authorization': f'Bearer {API_KEY}',
            'Content-Type': 'application/json'
        }
    )

    # 处理响应内容
    content = response.json()['choices'][0]['message']['content']

    # 从响应中提取JSON数组
    json_array_regex = r'\[[\s\S]*?\]'
    json_match = re.search(json_array_regex, content)

    if not json_match:
        return None
    try:
        return json.loads(json_match.group())
    except json.JSONDecodeError as e:
        return None


def image_to_text(image_url, style):
    from openai import OpenAI

    client = OpenAI(
        # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
        api_key=API_KEY,
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    response = client.chat.completions.create(
        model="qwen-vl-plus",
        # 此处以qwen-vl-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
        messages=[

            {"role": "user", "content": [
                {"type": "text", "text": "图片内容"},
                {"type": "image_url",
                 "image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}}
            ]}]
    )

    # 处理响应内容
    content = response.model_dump()['choices'][0]['message']['content']
    return content


# https://www.tsfansmerch.com:80/uploads/uploaded-image.png
# https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg
text = image_to_text("image_url", "style")
descriptions = generate_a_story(text, "style")
print(descriptions)